package com.hollycrm.hollysqm.analyzer.solr.filter;

import com.hollycrm.hollysqm.analyzer.solr.auth.SolrAuthentication;
import lombok.extern.log4j.Log4j;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by zhaihw on 2016/5/4.
 * solr鉴权filter
 */
@Log4j
public class SolrAuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始权限列表
        try {
            SolrAuthentication.INSTANCE.loadAvailableIps();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String ip = request.getRemoteAddr(); //获取请求IP
        if (SolrAuthentication.hasAuth(ip)) {
            chain.doFilter(request, response);
        }else{
            log.info("request ip " + ip);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("当前IP无权访问SolrCloud，请联系管理员授权!");
            response.flushBuffer();
        }
    }

    @Override
    public void destroy() {

    }
}
